2017-11-13 17 views
1

Iタイプとサイズは次のように関数名を介して符号化される非常に同様の動作を行い、異なる機能の多くを持っている次派生型名

int * operation_0_0_i(int a) { 
    int * result = new int[4]; 
    /* ... */ 
    return result; 
} 
int * operation_0_1_i(int a) { 
    int * result = new int[8]; 
    /* ... */ 
    return result; 
} 

float * operation_0_0_f(float a) { 
    float * result = new float[4]; 
    /* ... */ 
    return result; 
} 

float * operation_0_1_f(float a) { 
    float * result = new float[4]; 
    /* ... */ 
    return result; 
} 

代わりの異なる機能のこの混同量を有します私はテンプレートを使うことを考えました。私はそのような何かを行うことができますようにするため

template< typename T > 
struct A { 
    using type = T; 
    using array = std::array< T, 4 >; 
}; 

template< typename T > 
struct B { 
    using type = T; 
    using array = std::array< T, 8 >; 
}; 

:私の最初の試みはどこ派生型を実現するために、構造体をテンプレート

template< class U, typename T > 
T* operation0(T a) { 
    typename U<T>::array a; 
    /* ... */ 
    return a.data(); // I know, that this is unsafe. Its just for this example                      
} 

template< class U, typename T > 
T* operation1(T a) { 
    typename U<T>::array a;                      
    /* ... */ 
    return a.data(); 
} 

int main() { 
    int * res1 = operation1<A, int>(3); 
    int * res2 = operation2<B, int>(8); 
    /* ... */ 
    return 0; 
} 

残念ながら、これはコンパイルされません。 g ++はそれを教えてくれます

In function ‘T* operation0(T)’: error: expected nested-name-specifier before ‘U’ typename U<T>::array a; 

明らかに、この位置ではtypename指定子が間違っています。私はその指定を削除した場合でも、

‘U’ is not a template U<T>::array a; 

と文句を言い++グラムは、誰もが私が間違っているの何を、知っていますか?そして、おそらくstd::variantを使用して、さらに良いアプローチがありますか?お時間をありがとう;)

敬具

+0

をあなたはまた、「非型テンプレートパラメータ」に見ましたか? – AndyG

答えて

3

あなたはUクラスがテンプレートであることを伝えると、1つのパラメータ取る必要があります。

template<template <class > class U, typename T > 
T* operation0(T _a) { 
    typename U<T>::array a; 
    /* ... */ 
    return a.data();                
} 
関連する問題