gpt4 book ai didi

c++ - 类型分组 模板的显式实例化

转载 作者:搜寻专家 更新时间:2023-10-31 02:04:02 24 4
gpt4 key购买 nike

如果我有一个带有重载模板成员函数的模板类(使用 SFINAE),例如:

template <typename T>
struct Foo{
Foo(T elem);

template <typename U = T>
auto get() -> std::enable_if_t<std::is_same_v<U, int>, U>;
template <typename U = T>
auto get() -> std::enable_if_t<std::is_same_v<U, bool>, U>;
T elem_;
};

现在在我的 CPP 文件中,我必须定义并显式实例化:

template class Foo<int>;
template int Foo<int>::get<int>();
template class Foo<bool>;
template bool Foo<bool>::get<bool>();
// For all types...T, there will be two statements.

按类型进行分组实例化的不同可能方法有哪些 - 例如:

GroupedFooInit<int>(); // does both Foo<int> and Foo<int>::get<int>
GroupedFooInit<bool>(); // similar
.. and so on.

考虑到我必须使用 C++14,我可以想出 2 个解决方法,但不想要/喜欢:
1. :可能,但极力避免。
2. Definition in header, no explicit instantiation needed:可能,但是我正在处理一个巨大的 repo,其中我处理的文件几乎包含在所有地方 - 所以如果我走这条路,我的构建时间会很长即使是微小的变化。

Link to Code Snippet

最佳答案

你可以通过添加一个层来解决这个问题:

template <typename T>
struct Foo{
Foo(T elem);

T elem_;

T get(){
return do_get<T>();
}

private:

template <typename U = T>
auto do_get() -> std::enable_if_t<std::is_same<U, int>::value, U>;

template <typename U = T>
auto do_get() -> std::enable_if_t<std::is_same<U, bool>::value, U>;
};
//If definitions for the do_get functions are provided before these
//explicit template instantiation definitions, the compiler will certainly
//inline those definitions.
template class Foo<int>;
template class Foo<bool>;

关于c++ - 类型分组 模板的显式实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54274474/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com