c++ 是否可以为模板参数包的每个元素定义一个方法重载?

zzwlnbp8  于 2024-01-09  发布在  其他
关注(0)|答案(2)|浏览(133)

假设我有一个带有类型模板参数包的类模板,如

  1. template<typename... types>
  2. class Foo {};

字符串
有没有办法在Foo中定义方法,比如void bar(T x);,在参数包types中为每个类型T定义重载?

wr98u20j

wr98u20j1#

你可以让Foovoid bar(T x)继承每个基:

  1. template<typename T>
  2. struct FooBase {
  3. void bar(T x);
  4. };
  5. template<typename... types>
  6. struct Foo : FooBase<types>... {
  7. using FooBase<types>::bar...;
  8. };

字符串

nwnhqdif

nwnhqdif2#

你可以只使用一个模板bar

  1. template<typename... types>
  2. struct Foo
  3. {
  4. template <class T>
  5. void bar(T x)
  6. {
  7. }
  8. };

字符串
如果你只想限制types中的一个,那么你可以使用std::same_as概念:

  1. template<typename... types>
  2. struct Foo
  3. {
  4. template <class T>
  5. requires (... || std::same_as<T, types>)
  6. void bar(T x)
  7. {
  8. }
  9. };


但这将不接受可转换为types之一的参数(但不是其中之一)。所以你可以使用std::convertible_to来代替:

  1. template<typename... types>
  2. struct Foo
  3. {
  4. template <class T>
  5. requires (... || std::convertible_to<T, types>)
  6. void bar(T x)
  7. {
  8. }
  9. };


这仍然与实际的非模板化重载有一点不同,因为它不会生成“模糊重载错误”(如果您关心的话)。

展开查看全部

相关问题