0

例如,我有一堂课

// Require T has method T::A(arguments), T::B(arguments), since they will
// be used in the class template.
template<class T>
class Foo
{
    void Fun()
    {
        mT.A();
        mT.B();
    }
};

想要生成更具可读性的代码。有什么好的设计可以明确地让用户知道模板参数的要求吗?

4

1 回答 1

1

在 C++11 中,您可以将此答案static_assert结合使用,以提供更有用的编译器错误消息。例如:

#define HAS_MEM_FUNC(func, name)                                    \
    template <typename T>                                           \
    class name {                                                    \
        typedef char one;                                           \
        typedef long two;                                           \
        template <typename C> static one test( decltype(&C::func)); \
        template <typename C> static two test(...);                 \
    public:                                                         \
        enum { value = sizeof(test<T>(0)) == sizeof(char) };        \
    }

HAS_MEM_FUNC(A, has_A);
HAS_MEM_FUNC(B, has_B);

template<class T>
class Foo
{
public:
    void Fun()
    {
        static_assert(has_A<T>::value,
                      "Template parameter does not contain member function `A`."); 
        static_assert(has_B<T>::value,
                        "Template parameter does not contain member function `B`."); 

        mT.A();
        mT.B();
    }
    T mT;
};

现在代码

Foo<int> blah;
blah.Fun();

给出错误信息:

test.cpp:21:9: error: static assertion failed: Template parameter does not contain member function A.
test.cpp:23:9: error: static assertion failed: Template parameter does not contain member function B.
test.cpp:26:9: error: request for member ‘A’ in ‘((Foo<int>*)this)->Foo<int>::mT’, which is of non-class type ‘int’
test.cpp:27:9: error: request for member ‘B’ in ‘((Foo<int>*)this)->Foo<int>::mT’, which is of non-class type ‘int’
于 2013-07-04T19:29:00.207 回答