相关疑难解决方法(0)

C++ 11 constexpr函数的参数在模板参数中传递

这曾经在几周前工作:

template <typename T, T t>
T            tfunc()
{
    return t + 10;
}

template <typename T>
constexpr T       func(T t)
{
    return tfunc<T, t>();
}

int main()
{
    std::cout << func(10) << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但现在g++ -std=c++0x说:

main.cpp: In function ‘constexpr T func(T) [with T = int]’:
main.cpp:29:25:   instantiated from here
main.cpp:24:24: error: no matching function for call to ‘tfunc()’
main.cpp:24:24: note: candidate is:
main.cpp:16:14: note: template<class T, T t> T tfunc()
main.cpp:25:1: warning: control reaches …
Run Code Online (Sandbox Code Playgroud)

c++ gcc metaprogramming constexpr c++11

15
推荐指数
1
解决办法
9241
查看次数

具有相同签名的模板函数重载,为什么这有效?

最小程序:

#include <stdio.h>

#include <type_traits>

template<typename S, typename T>
int foo(typename T::type s) {
    return 1;
}

template<typename S, typename T>
int foo(S s) {
    return 2;
}

int main(int argc, char* argv[]) {
    int x = 3;
    printf("%d\n", foo<int, std::enable_if<true, int>>(x));

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

    1 
Run Code Online (Sandbox Code Playgroud)

为什么不给出编译错误?生成模板代码时,功能不会int foo(typename T::type search)int foo(S& search)签名相同吗?

如果您稍微更改模板函数签名,它仍然有效(正如我所期望的上面的示例):

template<typename S, typename T>
void foo(typename T::type s) {
    printf("a\n");
}

template<typename S, typename T>
void foo(S s) {
    printf("b\n");
}
Run Code Online (Sandbox Code Playgroud)

然而,这没有,但唯一的区别是一个具有int签名而另一个由第一个模板参数定义. …

c++ templates overloading

14
推荐指数
2
解决办法
1400
查看次数

std :: endl和variadic模板

码:

#include <iostream>

void out()
{
}

template<typename T, typename... Args>
void out(T value, Args... args)
{
    std::cout << value;
    out(args...);
}

int main()
{
    out("12345", "  ", 5, "\n"); // OK
    out(std::endl);              // compilation error
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

构建错误:

g++ -O0 -g3 -Wall -c -fmessage-length=0 -std=c++11 -pthread -MMD -MP -MF"main.d" -MT"main.d" -o "main.o" "../main.cpp"
../main.cpp: In function ‘int main()’:
../main.cpp:17:15: error: no matching function for call to ‘out(<unresolved overloaded function type>)’
../main.cpp:17:15: note: candidates are:
../main.cpp:3:6: note: void out() …
Run Code Online (Sandbox Code Playgroud)

c++ variadic-templates c++11

10
推荐指数
1
解决办法
525
查看次数

static_cast不按预期工作优先级

#include <iostream>
#include <cstdint>

template<int T> void foo()
{
  std::cout << "a" << std::endl;
}

template<uint8_t T> void foo()
{
  std::cout << "b" << std::endl;
}

int main()
{
  foo<static_cast<uint8_t>(42)> ();
  foo<static_cast<int>(42)>();
  return(0);
}
Run Code Online (Sandbox Code Playgroud)

知道为什么这不能按预期工作吗?

我的gcc 4.8.1抱怨一个模糊的调用,但static_cast不应该"修复"优先级规则,在这种情况下你有两种类型具有相同的优先级吗?

c++ templates overloading ambiguous-call c++11

9
推荐指数
1
解决办法
447
查看次数