简体   繁体   English

C++ 专用 function 模板别名语法

[英]C++ specialized function template alias syntax

I have我有

class ClassA {};
class ClassB {};

auto func_a() -> ClassA {
    return ClassA(); // example implementation for illustration. in reality can be different. does not match the form of func_b
}

auto func_b() -> ClassB {
    return ClassB(); // example implementation for illustration. in reality can be different. does not match the form of func_a
}

I want to be able to use the syntax我希望能够使用语法

func<ClassA>() // instead of func_a()
func<ClassB>() // instead of func_b()

(this is as part of a bigger template) (这是更大模板的一部分)

but I don't know how to implement this template specialization for the function alias.但我不知道如何为 function 别名实现此模板专业化。 Help?帮助? What is the syntax for this?这个的语法是什么?

[Edit] The answers posted so far do not answer my question, so I'll edit my question to be more clear. [编辑] 到目前为止发布的答案没有回答我的问题,所以我将编辑我的问题以更清楚。

The actual definition of func_a and func_b is more complex than just "return Type();". func_a 和 func_b 的实际定义比“return Type();”更复杂。 Also they cannot be touched.他们也不能被触摸。 So consider them to be所以认为他们是

auto func_a() -> ClassA {
    // unknown implementation. returns ClassA somehow
}
auto func_b() -> ClassB {
    // unknown implementation. returns ClassB somehow
}

I cannot template the contents of func_a or func_b.我无法模板化 func_a 或 func_b 的内容。 I need the template for func<ClassA|ClassB> to be specialized for each one of the two and be able to select the correct one to call我需要 func<ClassA|ClassB> 的模板专门用于两者中的每一个,并且能够 select 调用正确的模板

You might do something like (c++17):您可能会执行类似 (c++17) 的操作:

template <typename T>
auto func()
{
    if constexpr (std::is_same_v<T, ClassA>) {
        return func_a();
    } else {
        return func_b();
    }
}

Alternative for pre-C++17 is tag dispatching (which allows customization point): C++17 之前的替代方案是标签调度(允许定制点):

// Utility class to allow to "pass" Type.
template <typename T> struct Tag{};

// Possibly in namespace details
auto func(Tag<ClassA>) { return func_a(); }
auto func(Tag<ClassB>) { return func_b(); }

template <typename T>
auto func() { return func(Tag<T>{}); }

You can do it like this:你可以这样做:

#include <iostream>
#include <type_traits>

class A 
{
public:
    void hi()
    {
        std::cout << "hi\n";
    }
};

class B
{
public:
    void boo()
    {
        std::cout << "boo\n";
    }
};

template<typename type_t>
auto create()
{
    // optional : if you only want to be able to create instances of A or B
    // static_assert(std::is_same_v<A, type_t> || std::is_same_v<B, type_t>);

    type_t object{};
    return object;
}

int main()
{
    auto a = create<A>();
    auto b = create<B>();

    a.hi();
    b.boo();

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM