根据类型调用不同的功能

gar*_*ese 1 c++ conditional templates

我想根据类型调用模板化函数中的不同函数,如下所示:

template<typename T>
T func() {
    static_assert(std::is_same<T, int>::value || /* other allowed types */ , "Type not allowed");

    T ret {};
    // if T == int
    funcInt(&ret);
    // if T == /* other types */
    /* other functions */

}
Run Code Online (Sandbox Code Playgroud)

这样的事情可能吗?

我试过这个:

std::function< int(*T)> query;
if (std::is_same<T, int>::value) {
    query = funcInt;
}
Run Code Online (Sandbox Code Playgroud)

但这给了我一个错误:

错误:'T'不是指一个值

jro*_*rok 5

is_same可以在if语句中使用得很好:

if (std::is_same<T, int>::value>) { /* stuff */ }
if (std::is_same<T, float>::value) { /* other stuff */ }
Run Code Online (Sandbox Code Playgroud)

理论上,这个检查是在运行时完成的,编译器在编译时知道所有值,并且很可能会删除任何死的分支.缺点是整个代码func需要语法和形式良好,无论是什么T.这可能并不总是可行的.

正确的模板方式将是这样的:

template<typename>
struct helper;

template<>
struct helper<int> { static void do_work() { /* stuff */ } };

template<typename T>
T func()
{
    static_assert(std::is_same<T, int>::value || /* other allowed types */ , "Type not allowed");
    helper<T>::do_work();
}
Run Code Online (Sandbox Code Playgroud)

这允许您编写常用内容func并将其余内容放入专门化中.

OTOH,如果签名func真的很简单并且没有太多的代码重复,那么你也可以专注func自己.