如何用c++函数模板实现多调度

问题描述 投票:0回答:1

这就是我想要的:

struct type1{};

template <typename T, std::enable_if_t<std::is_xxx_v<T, type1>,void>* = nullptr>
my_fuction(const T& obj)
{
    std::cout << "operation on type1" << std::endl;
}

template <typename T, std::enable_if_t<!std::is_xxx_v<T, type1>,void>* = nullptr>
my_fuction(const T& obj)
{
    std::cout << "operation on other types" << std::endl;
}

几天后,我必须添加另一种类型

struct type2{};

但是我如何为 type1 type2 和其他类型实现 my_fuction 呢? 我可以这样写:

struct type2{};

template <typename T, std::enable_if_t<std::is_xxx_v<T, type1>,void>* = nullptr>
my_fuction(const T& obj)
{
    std::cout << "operation on type1" << std::endl;
}

template <typename T, std::enable_if_t<std::is_xxx_v<T, type2>,void>* = nullptr>
my_fuction(const T& obj)
{
    std::cout << "operation on type2" << std::endl;
}

// my_function for other types
template <typename T, std::enable_if_t<!std::is_xxx_v<T, type1> && !std::is_xxx_v<T, type2>,void>* = nullptr>
my_fuction(const T& obj)
{
    std::cout << "operation on other types" << std::endl;
}

但这不是一个好方法,因为有一天,我添加了 struct type3{},我必须为 type3 添加一个新的 func(我可以接受这一点),但我还必须更改其他类型的代码,而我不这样做不想。

我想要的是如果我添加一个新的type3,是否有可能我只为type3添加一个新的重载函数,而其他类型的代码不需要改变。

templates c++17 overloading
1个回答
0
投票

根据您使用的

std::is_xxx_v
,您也许可以使用 模板专业化。首先声明使用任何类型参数的默认函数:

template<typename T>
void my_function_specialization(const T& obj) {
    std::cout << "operation on other types" << std::endl;
}

然后您可以将函数专门化为您想要的类型

template<>
void my_function_specialization(const type1& obj) {
    std::cout << "operation on type1" << std::endl;
}

template<>
void my_function_specialization(const type2& obj) {
    std::cout << "operation on type2" << std::endl;
}
/*
 and so on...
*/

否则你可以使用

if constexpr
来区分不同的情况:

template<typename T>
void my_function_if_constexpr(const T& obj) {
    if constexpr (std::is_same_v<type1, T>) {
        std::cout << "operation on type1" << std::endl;
    } else if constexpr (std::is_same_v<type2, T>) {
        std::cout << "operation on type2" << std::endl;
    } else if constexpr (/* and so on... */) {
        /* ... */
    } else {
        std::cout << "operation on other types" << std::endl;
    }
}

查看演示

© www.soinside.com 2019 - 2024. All rights reserved.