c++ - 模板静态函数模板类类型推导

标签 c++ templates

我想在单例模板类中创建静态函数,这样可以推导出模板类的类型。 问题是,从模板类调用静态函数需要显式类型。 我想出的唯一解决方法是模板函数而不是模板成员函数。

这是一个例子。问题是 foo4 部分不工作

template <class T>
class Foo
{
private:
    Foo() {}
    Foo(const Foo&) = delete;
    Foo& operator= (const Foo&) = delete;

public:
    static auto& Instance()
    {
        static Foo foo{};
        return foo;
    }

    template<class K> static
    auto& DeductInstance(const K&)
    {
        static Foo<K> foo{};
        return foo;
    }

};

template<class K>
auto& DeductInstance(const K&)
{
    return Foo<K>::Instance();
}

void main()
{
    auto& foo1 = Foo<int>::Instance(); //OK
    auto& foo2 = Foo<int>::Instance(); //OK (return same example as foo1)
    auto& foo3 = DeductInstance(123); //OK
    auto& foo4 = Foo::DeductInstance(123); //NOT WORKING
}

最佳答案

您要求的语法在理论上可以使用注入(inject)的类名。那将使Foo::解决一个特定的,无关的Foo<x>:: .这是一个例子:

struct BaseFoo {
    template<class K> static
    auto& DeductInstance(const K&);
};

template <class T>
struct Foo  {
    static auto& Instance() {
        static Foo foo{};
        return foo;
    }
};

template<>
struct Foo<void> : private BaseFoo {
    using BaseFoo::DeductInstance;
};

template<typename K>
auto& BaseFoo::DeductInstance(const K&)
{
    return Foo<K>::Instance();
}

using MakeFooAvailable = Foo<void>;

struct Dummy : MakeFooAvailable {
    auto& bar() {
        // Syntax working
        return Foo::DeductInstance(234);
    }
};

在类里面Dummy , 有一个基类的注入(inject)类名 Foo , 解析为 Foo<void> .然后,Foo<void>正在制作BaseFoo::DeductInstance可用于其范围内的名称解析。


我建议不要使用此解决方案,因为它很聪明。聪明通常意味着令人惊讶。程序员不希望看到 Foo作为非模板时。我认为最好的解决方案是:

auto& foo1 = Foo<int>::Instance(); //OK

越简单越好。

关于c++ - 模板静态函数模板类类型推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55146279/

相关文章:

c++ - Qt 编译问题 w/MySQL - Mac OS X

c++ - 通过 Rcpp 正确注册插件以使用 Eigen

c++ - 初始化引用成员:语法不同的原因

c++ - 从模板类继承繁琐

c++ - 如何在子类中重载模板函数(专门)?

c++ - 函数包装器中的堆栈分配/函数中的分配

c++ - 重载运算符和修改字符串

C++ boost::variant 泛型转换器

templates - 如何从 template.FuncMap 返回 HTML 模板?

templates - Ember,我的模板不会在属性更改时更新