4
target() 템플릿 메서드를 사용하여 std :: functions을 비교하기위한 일반 코드를 작성하려고합니다. 여기 내 제네릭이 아닌 샘플 코드입니다 :Variadic 템플릿 질문
#include <cstdio>
#include <functional>
static void bar() {}
static void baz() {}
bool cmp(std::function<void()> f1, std::function<void()> f2)
{
void (**t1)() = f1.target<void(*)()>();
void (**t2)() = f2.target<void(*)()>();
return (!t1 && !t2) || (t1 && t2 && *t1 == *t2);
}
int main(int argc, char *argv[])
{
std::function<void()> f1(bar), f2(baz), f3(bar);
printf("equal: %d\n", cmp(f1, f3));
printf("non-equal: %d\n", cmp(f1, f2));
return 0;
}
이 컴파일 및 GCC 4.6.1 -std = C++와 잘 실행 - X.
#include <cstdio>
#include <functional>
static void bar() {}
static void baz() {}
template<typename Result, typename ... Args>
bool cmp(std::function<Result(Args...)> f1, std::function<Result(Args...)> f2)
{
Result (**t1)(Args...) = f1.target<Result(*)(Args...)>();
Result (**t2)(Args...) = f2.target<Result(*)(Args...)>();
return (!t1 && !t2) || (t1 && t2 && *t1 == *t2);
}
int main(int argc, char *argv[])
{
std::function<void()> f1(bar), f2(baz), f3(bar);
printf("equal: %d\n", cmp(f1, f3));
printf("non-equal: %d\n", cmp(f1, f2));
return 0;
}
오류 코드는 다음과 같습니다 :
functional.cpp: In function ‘bool cmp(std::function<_Res(_ArgTypes ...)>, std::function<_Res(_ArgTypes ...)>)’:
functional.cpp:11:44: error: expected primary-expression before ‘(’ token
functional.cpp:11:46: error: expected primary-expression before ‘)’ token
functional.cpp:11:52: error: expected primary-expression before ‘...’ token
functional.cpp:11:58: error: expected primary-expression before ‘)’ token
functional.cpp:12:44: error: expected primary-expression before ‘(’ token
functional.cpp:12:46: error: expected primary-expression before ‘)’ token
functional.cpp:12:52: error: expected primary-expression before ‘...’ token
functional.cpp:12:58: error: expected primary-expression before ‘)’ token
어떤 힌트 그러나 나는 구문 분석 오류 코드와 컴파일러가 실패 다음과 같은 일반적인 CMP 기능을 컴파일하기 위해 노력하고있어 때?
감사합니다. 하나; 이 문법은 나에게 꽤 새로운 것이다. 사용법에 대한 정보를 좀 주시겠습니까? – kyku
@kyku - 컴파일러는 템플릿이라는 것을 알아야합니다. 그렇지 않으면'f1.target'이 템플릿의 일부가되고 비교 대상이 아니라는 것을 알아야합니다. –
@kyku : 자세한 내용은 다음 FAQ를 참조하십시오. [[템플릿, .template 및 템플릿에 대한 구문은 무엇입니까?] (http://www.comeaucomputing.com/techtalk/templates/#templateprefix) – ildjarn