小编tho*_*mas的帖子

如何在模板类型上使用某些类型特定的函数(例如 std::string 或 std::vector 等的 .size() )?

如果可能,我如何在具有模板类型的函数中使用某些特定于类型的函数(例如.size()for: std::stringor std::vectoror ...),确保当我使用该特定于类型的函数时我实际上正在调用它以正确的类型作为参数?也许我错了,如果是的话,请向我解释我必须做什么。

#include <iostream>
#include <string>

template <typename T>
std::string func(T& number) {
    if (typeid(T) == typeid(std::string)) {
        unsigned short int size = number.size();// !
        return " is a string";
    }
    else if (typeid(T) == typeid(int)) {
        return " is an int";
    }
    //...
}

int main() {
    std::string name = "Anthony";
    int age = 8;
    std::cout << name /*<< func(name) */<< '\n' << age << func(age) << '.';
    return 0;
}

Run Code Online (Sandbox Code Playgroud)

我知道在上面的代码中:

unsigned …
Run Code Online (Sandbox Code Playgroud)

c++ template-meta-programming

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

为什么这个模板函数无法识别 lamda 的返回类型?

此模板函数无法识别 lamda 的返回类型,甚至指定它取消注释 '->void'。

为什么会发生这种情况?

我可以做什么来规避这个问题?

#include<iostream>
#include<array>
template<typename T, typename S, size_t SIZE>
void for_each(std::array<T,SIZE>& arr, S(*func)(int&))
{
    for (auto i{0}; i != arr.size(); ++i)
        func(arr[i]);
}
int main()
{
    std::array<int, 5> five_elems{10, 20, 30, 40, 50};
    for_each(five_elems, [](int& ref)/*->void*/{ref *= 2; std::cout << ref << ' '; });
    //for (auto i : five_elems)
    //    i*=2;
    for (const auto i : five_elems)
        std::cout << i << ' ';
}

Run Code Online (Sandbox Code Playgroud)

c++ lambda templates

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

为什么当我的 char 变量达到 [del] 字符 (127) 值时,我的程序会进入无限循环?

这是我的代码:

#include <iostream>

int main()
{
    char x = 32;
    while (x <= 126) {
        std::cout << x << "\n";
        x += 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

到这里为止,一切顺利,但如果我将代码更改为:

#include <iostream>

int main()
{
    char x = 32;
    while (x <= 127 /* here the "bad" change */ ) {
        std::cout << x << "\n";
        x += 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

为了尝试打印 [del] 字符,我的程序进入无限循环并开始打印许多我不想要的其他字符。为什么?

c++ ascii infinite-loop while-loop

0
推荐指数
1
解决办法
228
查看次数

如何通过“查看”其二进制值的最后一位来检查 int 变量是偶数还是奇数?

如何通过查看变量的最后一位来检查存储在变量中的整数是偶数还是奇数?(我已经看到很多答案通过提醒进行模运算来确定它,但是,我的意思是,由于二进制数的最后一位数字可以是 0 xor 1,并且假设它是 0,则该数字是偶数,否则数字是奇数,直接看最后一位数字不是更快吗?)

c++ performance

0
推荐指数
2
解决办法
402
查看次数