如何明确让用户知道模板参数的要求?

时间:2013-07-04 18:34:38

标签: c++ templates readable

例如,我有一个班级

// 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();
    }
};

想要生成更易读的代码。任何好的设计都明确让用户知道模板参数的要求吗?

1 个答案:

答案 0 :(得分:1)

在C ++ 11中,您可以将this answerstatic_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’