在我目前正在撰寫的類中,我認為它的大部分私有成員變數保持const. 因此,我選擇使用未在頭檔案中完全宣告的初始化物件:
// foo.h
template<typename T>
class Foo {
const int *const memberVariable; // Important detail: pointer to a heap-allocated array
const int otherMemberVariable;
...
Foo(class FooInitializer &&initializer);
public:
Foo(int constructorArgument, ...);
}
// foo.cpp
class FooInitializer {
int *memberVariable; // Important detail: pointer to a heap-allocated array
int otherMemberVariable;
...
FooInitializer(int constructorArgument, ...) : memberVariable(constructorArgument, ...), ... {
cuda_function(&memberVariable, &otherMemberVariable, ..., constructorArgument, ...);
...
}
}
Foo::Foo(FooInitializer &&initializer) : memberVariable(std::move(initializer.memberVariable)), ... {}
Foo::Foo(int constructorArgument, ...) : Foo({constructorArgument, ...}) {}
但是,如果建構式引數或成員變數之一必須是型別引數型別,這似乎會崩潰:
// foo.h
template<typename T>
class Foo {
const int *const memberVariable; // Important detail: pointer to a heap-allocated array
const int otherMemberVariable;
...
Foo(class FooInitializer<T> &&initializer);
public:
Foo(int constructorArgument, ...);
}
// foo.cpp
template<typename T>
class FooInitializer {
int *memberVariable;
int otherMemberVariable;
...
FooInitializer(int constructorArgument, ...) : memberVariable(constructorArgument, ...), ... {
cuda_function(&memberVariable, &otherMemberVariable, ..., constructorArgument, ...);
...
}
}
template<typename T>
Foo<T>::Foo(FooInitializer<T> &&initializer) : memberVariable(std::move(initializer.memberVariable)), ... {}
template<typename T>
Foo<T>::Foo(int constructorArgument, ...) : Foo({constructorArgument, ...}) {}
I have tried some alternative syntaxes (such as Foo<T>::Foo(template<> FooInitializer<T> &&initializer) to no avail. I am opposed to temporary heap allocation, and I am trying to avoid introducing FooInitializer into the header's namespace due to essentially duplicate declarations of the member variables. I was considering the possibility of storing a const FooInitializer instance itself as the only member variable of Foo, but unfortunately that would make variables like memberVariable in the example above int *const, not const int *const. They cannot be C containers because they are allocated in device memory by CUDA functions.
Is there an alternative approach I have not considered?
uj5u.com熱心網友回復:
Foo(class FooInitializer<T> &&initializer);
雖然您可以在函式宣告 ( int bar(struct S s);) 中宣告(非模板)類,但我認為您不能用于模板類。
FooInitializer由于成員變數的基本重復宣告,我試圖避免引入標頭的命名空間。
但您仍然可以轉發宣告該類:
template <typename> class FooInitializer;
template<typename T>
class Foo
{
// ...
Foo(FooInitializer<T> &&initializer);
// ...
};
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/350159.html
下一篇:<br/>換行
