2

C++11 でカスタム メタプログラミング テストを作成するにはどうすればよいですか? 私はこのようなものを書きたいと思います:

#include <type_traits>
#include <iostream>

struct A {};

template <typename T>
struct foo {
    typedef typename std::conditional<std::is_pointer<T>::value,
                                      typename std::remove_pointer<T>::type,
                                      T>::type type;
};

template <typename A, typename B>
struct test1{typedef typename std::is_same<A, B>::value result;};

template <typename A, typename B>
struct test2{typedef typename std::is_same<A, typename foo<B>::type>::value result;};

template <typename A, typename B>
void testAll() {
    std::cout << std::boolalpha;
    std::cout << "test1: " << typename test1<A,B>::result << std::endl; // ERROR: expected ‘(’ before ‘&lt;<’ token
    std::cout << "test2: " << typename test2<A,B>::result << std::endl; // ERROR: expected ‘(’ before ‘&lt;<’ token
    // ...
}

int main()
{  
    typedef A type1;
    testAll<A, type1>();
    typedef const A* type2;
    testAll<A, type2>();
    // ...
}

hereから is_same 実装の可能性を見ました。そのようなものが必要ですか?

これを書くことが可能です:

std::cout << "test1: " << std::is_same<A, B>::value << std::endl;

私はこれを書きたいと思います:

 std::cout << "test1: " << test1<A, B>::result << std::endl;
4

1 に答える 1

2

typenamebeforeを使用していますが、タイプではなくvalueになりtest1<A,B>::resultたいため、これは不適切です。同じ理由で、内部で型エイリアスとして定義するべきではありません:によって返される同じが必要なだけです(これは、型名ではなくメンバー変数です)。resulttest1<>std::is_same<>::valuestatic const bool

このように書くことができます:

template <typename A, typename B>
struct test1
{ 
    static const bool result = std::is_same<A, B>::value;
};

次の行がコンパイルされるように:

std::cout << "test1: " << test1<A,B>::result << std::endl;

ただし、あなたの特性は(の代わりに)test1<>のエイリアスにすぎず、C++1 はエイリアス テンプレートをサポートします。std::is_same<>resultvalue

template <typename A, typename B>
using test1 = std::is_same<A, B>;

これにより、次のことが可能になります。

std::cout << "test1: " << test1<A,B>::value << std::endl;

この特性は、型エイリアスとして定義されているが、型ではなく値であるtest2<>という点で、同様の問題を抱えています。resultstd::is_same<A, typename foo<B>::type>::value

したがって、もう一度次のように書き換えることができます。

template <typename A, typename B>
struct test2
{
    static const bool result = std::is_same<A, typename foo<B>::type>::value;
};

次の行がコンパイルされるように:

std::cout << "test2: " << test2<A, B>::result << std::endl;

ただし、エイリアス テンプレートを定義することもできます。

template <typename A, typename B>
using test2 = std::is_same<A, typename foo<B>::type>;
于 2013-03-13T19:14:36.793 に答える