Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何明确地让用户知道模板参数的要求?_C++_Templates_Readable - Fatal编程技术网

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

C++ 如何明确地让用户知道模板参数的要求?,c++,templates,readable,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(); } }; //requiret有方法T::A(参数),T::B(参数),因为它

例如,我有一门课

// 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();
    }
};
//requiret有方法T::A(参数),T::B(参数),因为它们将
//可以在类模板中使用。
模板
福班
{
虚无乐趣()
{
山A();
山B();
}
};
希望生成更可读的代码。在C++11中,是否有明确让用户知道模板参数要求的良好设计?

可以与结合使用,以提供更有用的编译器错误消息。例如:

#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;
};
#定义有_MEM_FUNC(FUNC,name)\
模板\
类名{\
类型1\
长两个\
模板静态一个测试(decltype(&C::func))\
模板静态二次试验(…)\
公众:\
枚举{value=sizeof(test(0))==sizeof(char)}\
}
HAS_MEM_FUNC(A,HAS_A);
HAS_MEM_FUNC(B,HAS_B);
模板
福班
{
公众:
虚无乐趣()
{
静态断言(有一个::值,
“模板参数不包含成员函数`A`.”;
静态_断言(具有_B::value,
“模板参数不包含成员函数`B`.”;
山A();
山B();
}
T-mT;
};
现在是代码

Foo<int> blah;
blah.Fun();
Foo-blah;
无聊的;无聊的;
给出错误消息:

test.cpp:21:9:错误:静态断言失败:模板参数不包含成员函数A。
test.cpp:23:9:错误:静态断言失败:模板参数不包含成员函数B。
test.cpp:26:9:错误:请求成员'A'in'((Foo*)this)->Foo::mT',它是非类类型'int'
test.cpp:27:9:错误:请求成员'B'在'((Foo*)this)->Foo::mT',它是非类类型'int'

tags也许吧?我们能给你的唯一正确答案是:以这样或那样的方式记录它。至于如何妥善记录,每个人都会有不同的看法。但是,正如@CaptainObvlious所提到的,
doxygen
是一个从代码/注释生成文档的好工具。