以下代碼類似于我的真實應用程式。我有一個高度依賴 int 值的類定義s,當呼叫具有兩個不同值的兩個類的實體時s,我需要撰寫兩次呼叫函式,我們有沒有像using rightInst = std::conditional_t<use10, instA, instB>;實體化之前使用的那樣更簡單的方法。
template<int s>
class classAdef{
public:
// some code related to 's'
classAdef(){
// some code related to 's'
}
int operator(int a, int b, int c){
// some code related to 's'
printf("class is called \n");
return 0;
}
}
bool use10 = true;
using def10 = classAdef<10>;
using def100 = classAdef<100>;
def10 instA;
def100 instB;
if (use10){
instA(1, 2, 3);
} else{
instB(1, 2, 3);
}
// this code doesnot work, but want something like this to simpilify the function calling
using rightInst = std::conditional_t<use10, instA, instB>;
rightInst(1, 2, 3);
uj5u.com熱心網友回復:
您可以將所選實體存盤在 a 中std::variant并用于std::visit呼叫您的方法。您仍然需要某種條件(這里我使用三元)來存盤正確的實體,因此對于這種特定情況,這似乎不是很干凈。
#include <cstdio>
#include <variant>
template<int s>
class classAdef{
public:
// some code related to 's'
classAdef(){
// some code related to 's'
}
int operator()(int a, int b, int c){
// some code related to 's'
printf("class %d is called \n", s);
return 0;
}
};
int main()
{
bool use10 = true;
using def10 = classAdef<10>;
using def100 = classAdef<100>;
def10 instA;
def100 instB;
std::variant<def10, def100> var;
use10 ? var = instA : var = instB;
std::visit([](auto& inst){ inst(1,2,3); }, var);
}
https://godbolt.org/z/o9n9jb7eh
uj5u.com熱心網友回復:
多型是這里的一個選項,因為沒有什么可以阻止模板類具有多型基并覆寫繼承的虛擬;
例如
#include <iostream>
#include <memory>
class Base
{
public:
Base() {};
virtual int operator()(int a, int b, int c) = 0;
virtual ~Base() {};
};
template<int s> class classAdef : public Base
{
public:
int operator()(int a, int b, int c)
{
// some code related to 's'
std::cout << s << " class is called \n";
return 0;
};
};
int main()
{
bool use10 = true;
std::unique_ptr<Base> object;
if (use10)
object = std::make_unique<classAdef<10> >();
else
object = std::make_unique<classAdef<100> >();
(*object)(1,2,3);
}
決定呼叫哪個多載的所有邏輯都在實體化物件的程序中解決。
使用unique_ptris 來簡化清理(完成后銷毀物件)。
鑒于您的描述,我不會使用運算子函式 - 一個適當命名的虛擬函式(由 呼叫object->virtualFun(1,2,3))就足夠了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/415746.html
標籤:
