c++ - 如何使这个模板代码工作?

标签 c++ templates

模板代码是这样的:

template <class type1>
struct DefaultInstanceCreator {
    type1 * operator ()() {
        return new type1;
    }
};

template < class type1
, class InstanceCreator = DefaultInstanceCreator<type1> >
class objectCache 
{
    public:
        objectCache (InstanceCreator  & instCreator) 
          :instCreator_ (instCreator) {}
        type1* Get() {
            type1 * temp = instCreator_ ();
        }
    private:
        InstanceCreator instCreator_;
};

此代码适用于像这样的对象类:

class A{
public:
    A(int num){
        number = num;
    }
    int number;
    struct CreateInstance {
        CreateInstance (int value) : value_ (value) {}
        A * operator ()() const{
            return new A(value_);
        }
        int value_;
    };
};
objectCache< A, A::CreateInstance > intcache(A::CreateInstance(2));
    A* temp = intcache.Get();
    cout << temp->number <<endl;

当我尝试使用 int、string 等类型的模板时...

objectCache< int > intcache();
int* temp = intcache.Get();
*temp = 3;
cout <<temp <<endl;

我在“'.Get' must have class/struct/union”的左边得到 E, 我找不到问题出在哪里

当我变成

objectCache< int > intcache;

我得到“'objectCache':没有合适的默认构造函数可用”

使用

objectCache< int > intcache(DefaultInstanceCreator<int>());

我也忘记了“'.Get' 必须有类/结构/union ”。

最佳答案

在这里,您没有将参数传递给 intcache构造函数:

objectCache< int > intcache();
int* temp = intcache.Get();

这会导致第一行恢复为众所周知的 "most vexing parse" C++,简而言之,你在声明 intcache作为一个不带参数并返回 objectCache<int> 的函数.

也许你的意思是:

objectCache< int > intcache;

但您可能想传递一个工厂:

objectCache< int > intcache((DefaultInstanceCreator<int>()));

关于c++ - 如何使这个模板代码工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1170522/

相关文章:

c++ - 错误 : expected type-specifier before Class

c++ - 将异常转换为可选的 : cant resolve overloaded function type

c++ - 如何避免在 C++ 项目(XCode)中的其他机器上加载动态库?

c++ - 如何从可变参数模板参数创建 std::tuple<>?

c++ - 如何在 do/while 循环中获取用户输入?

c++ - 为什么在第二次调用时使用默认参数时此模板特化会失败?

C++ 错误 : was not declared in this scope with private after public

c++ - 空指针错误

python - Django,在模板中创建变量并赋值

c++ - 从模板参数中提取 simd vector 长度以用于本地类型