gpt4 book ai didi

c++ - 如何构建具有特定签名的函数概念?

转载 作者:搜寻专家 更新时间:2023-10-31 02:05:49 25 4
gpt4 key购买 nike

我正在使用概念编写一些通用软件,我想检查结构上是否存在带有 (void)(int,int) 签名的特定函数符号名称。为此,我一直在考虑通过模板特化来解决这个问题,但我有点迷路了。

我想要的是一些可以工作的东西,如果不满足这样的概念,则可以通过编译时错误:

struct TypeA {
// Passes concept
void process (int a ,int b) const {};
};

struct TypeB {
// Does not pass concept
void process (float a) const {};
};

struct TestConcepts {
/* concept code here */
TestConcepts(T t) {
process_concept(t.process);
};
};

int main(void) {
// Should pass
TestConcept(TypeA{});
// Should throw error
TestConcept(TypeB{});
return 0;
}

我很难填补空白,但这是我目前所拥有的:

struct TestConcepts {
/* concept code here */
struct process_concept {
process_concept((V*)(IA,IB)){
if (is_integral<IA>::value && is_integral<IB>::value && is_same<V, void>) {
return;
}
static_assert(false, "You must provide function called process of type (void)(int,int)");
};
};
TestConcepts(T t) {
process_concept(&t.process);
};
};

不幸的是,这不起作用。我怎样才能使这个函数签名正确?

最佳答案

使用返回已声明函数指针的函数怎么样?

struct TypeA {
// Passes concept
void process (int a ,int b) const {};
};

struct TypeB {
// Does not pass concept
void process (float a) const {};
};

template<typename T>
auto TestConcepts(T) -> void(T::*)(int, int) const
{
return &T::process;
}

int main(void) {
// Should pass
TestConcepts(TypeA{});
// Should throw error
TestConcepts(TypeB{});
return 0;
}

输出:

Error(s):

source_file.cpp: In instantiation of ‘void (T::* TestConcepts(T))(int, int) const [with T = TypeB]’:
source_file.cpp:26:23: required from here
source_file.cpp:19:16: error: cannot convert ‘void (TypeB::*)(float) const’ to ‘void (TypeB::*)(int, int) const’ in return
return &T::process;
^

编辑:更多选项

如果你想包含 void process(long int a, long int b) const;void process(int a, int b, int c=0) const;,就像 aschepler 建议的那样,您可以使用类型特征。

struct TypeA {
// Passes concept
void process(int a, int b) const {};
};

struct TypeB {
// Does not pass concept
void process(float a) const {};
};

struct TypeC {
// Passes concept
void process(long int a, long int b) const {};
};

struct TypeD {
// Passes concept
void process(int a, int b, int c = 0) const {};
};

struct TypeE {
// Does not pass concept
void process(int a, int b, int c) const {};
};

#include <type_traits>
template<typename T, typename A1, typename A2, typename... An>
typename std::enable_if<
std::is_integral<A1>::value &&
std::is_integral<A2>::value
>::type
TestProcess(const T& t, void(T::*)(A1, A2, An...) const) {
t.process(1, 2);
};

template<typename T>
void TestConcepts(const T& t)
{
TestProcess(t, &T::process);
}

int main(void) {
// Passes
TestConcepts(TypeA{});
// Throws compilation error
TestConcepts(TypeB{});
// Passes
TestConcepts(TypeC{});
// Passes
TestConcepts(TypeD{});
// Throws compilation error
TestConcepts(TypeE{});

return 0;
}

关于c++ - 如何构建具有特定签名的函数概念?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51226381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com